<template>
  <div>
    <el-button :disabled="!category3Id" type="primary" icon="el-icon-plus" @click="addAttrValue">添加属性</el-button>
    <el-table :data="attrList">
      <el-table-column label="序号" type="index" />
      <el-table-column label="属性名" prop="attrName" />
      <el-table-column label="属性值列表">
        <template v-slot="{row}">
          <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id">{{ attrValue.valueName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{row,$index}">
          <el-tooltip class="item" effect="dark" content="编辑属性" placement="top">
            <el-button size="small" type="warning" icon="el-icon-edit" @click="editOneAttr(row)" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除属性" placement="top">
            <el-button size="small" type="danger" icon="el-icon-delete" @click="delOneAttr(row,$index)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { reqGetAttrList, reqDelAttr } from '@/api/product/attr'
import { mapState } from 'vuex'
export default {
  name: 'AttrList',
  data() {
    return {
      attrList: []
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  watch: {
    category3Id: {
      immediate: true, // 第一次加载就需要执行
      async handler() {
        const { category1Id, category2Id, category3Id } = this
        if (!category3Id) {
          this.attrList = [] // 清空不渲染数据
          return // 如果没有值 什么都不做
        }
        this.loading = true
        // 如果有值，则需要发送请求
        const result = await reqGetAttrList({
          category1Id,
          category2Id,
          category3Id
        })
        //  console.log(result);
        if (result.code === 200) {
          this.loading = false
          this.attrList = result.data
        }
      }
    }
  },
  methods: {
    // 1.编辑属性按钮
    editOneAttr(row) {
      this.$emit('update:visible', false)
      this.$emit('setAttr', row)
    },
    // 2.点击添加属性
    addAttrValue() {
      this.$emit('update:visible', false)
      this.$emit('setAttr', {
        attrName: '',
        attrValueList: []
      })
    },
    // 3.删除属性
    async delOneAttr(row, index) {
      this.$confirm('您真的要删除此属性吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await reqDelAttr(row.id)
        if (res.code === 200) {
          this.attrList.splice(index, 1)
          this.$message.success('删除属性成功')
        } else {
          this.$message.error('删除属性失败')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style>

</style>
